package cn.wolfcode.car.business.web.controller;

import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.domain.StatementItem;
import cn.wolfcode.car.business.query.StatementItemQuery;
import cn.wolfcode.car.business.service.IStatementItemService;
import cn.wolfcode.car.business.service.IStatementService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.web.AjaxResult;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("/business/statementItem")
public class StatementItemController {
    //前缀
    private static final String prefix = "/business/statementItem/";
    @Autowired
    private IStatementService statementService;
    @Autowired
    private IStatementItemService statementItemService;
    /***************************   进入页面开始    *****************************/


    /***************************   进入页面结束    *****************************/

    //根据不同的状态 进入不同的页面  消费中 || 已支付
    @RequestMapping("/itemDetail")
    public String itemDetail(Long statementId, Model model) {
        //查询当前结算单 并且共享
        Statement statement = statementService.get(statementId);
        model.addAttribute("statement", statement);
        if (Statement.STATUS_CONSUME.equals(statement.getStatus())) {
            //消费中
            return prefix + "itemEdit.html";
        } else {
            //已支付
            return prefix + "itemDetail.html";
        }
    }

    //查询页面数据
    @RequestMapping("/query")
    @ResponseBody
    public TablePageInfo<StatementItem> query(StatementItemQuery qo) {
        return statementItemService.query(qo);
    }
    //点击保存   接参数是集合 需要贴  @RequestBody 要不计算机不认识
    @RequestMapping("/saveItems")
    @ResponseBody
    public AjaxResult saveItems(@RequestBody List<StatementItem> list){
        statementItemService.saveItems(list);
        return AjaxResult.success();
    }
    //点击支付
    @RequestMapping("/pay")
    @ResponseBody
    public AjaxResult pay(Long statementId){
        statementService.pay(statementId);
        return AjaxResult.success();
    }
    //导出
    @RequestMapping("/export")
    @ResponseBody
    public void export(HttpServletResponse response,Long statementId) throws Exception {
        String fileName ="statementItemData.xlsx";
        //设置响应头
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        //需要将下载的数据存放在内存中的workbook 我们就需要将Workbook 写到响应流中
        Workbook wb = statementItemService.export(statementId);
        wb.write(response.getOutputStream());
        wb.close();
    }
}
